const { pool } = require('../config/database');

class Menu {
  // 获取所有菜单
  static async findAll() {
    try {
      const [rows] = await pool.execute('SELECT * FROM menus ORDER BY order_num');
      return rows;
    } catch (error) {
      throw new Error(`获取菜单列表失败: ${error.message}`);
    }
  }

  // 根据角色ID获取菜单
  static async findByRoleId(roleId) {
    try {
      const [rows] = await pool.execute(
        `SELECT m.* FROM menus m 
         INNER JOIN role_menus rm ON m.id = rm.menu_id 
         WHERE rm.role_id = ? 
         ORDER BY m.order_num`,
        [roleId]
      );
      return rows;
    } catch (error) {
      throw new Error(`获取角色菜单失败: ${error.message}`);
    }
  }

  // 构建菜单树结构
  static buildMenuTree(menus, parentId = null) {
    return menus
      .filter(menu => menu.parent_id === parentId)
      .map(menu => ({
        ...menu,
        children: this.buildMenuTree(menus, menu.id)
      }));
  }

  // 创建菜单
  static async create(menuData) {
    try {
      const { name, parent_id = null, type, order_num } = menuData;
      const [result] = await pool.execute(
        'INSERT INTO menus (name, parent_id, type, order_num) VALUES (?, ?, ?, ?)',
        [name, parent_id, type, order_num]
      );
      return { id: result.insertId, ...menuData };
    } catch (error) {
      throw new Error(`创建菜单失败: ${error.message}`);
    }
  }

  // 更新菜单
  static async update(id, menuData) {
    try {
      const fields = [];
      const params = [];
      for (const key of ['name', 'parent_id', 'type', 'order_num']) {
        if (menuData[key] !== undefined) {
          fields.push(`${key} = ?`);
          params.push(menuData[key]);
        }
      }
      if (fields.length === 0) throw new Error('没有可更新字段');
      params.push(id);
      await pool.execute(`UPDATE menus SET ${fields.join(', ')} WHERE id = ?`, params);
      return await this.findById(id);
    } catch (error) {
      throw new Error(`更新菜单失败: ${error.message}`);
    }
  }

  // 删除菜单
  static async delete(id) {
    try {
      await pool.execute('DELETE FROM menus WHERE id = ?', [id]);
      return true;
    } catch (error) {
      throw new Error(`删除菜单失败: ${error.message}`);
    }
  }

  // 根据ID获取菜单
  static async findById(id) {
    try {
      const [rows] = await pool.execute('SELECT * FROM menus WHERE id = ?', [id]);
      return rows[0] || null;
    } catch (error) {
      throw new Error(`获取菜单失败: ${error.message}`);
    }
  }
}

module.exports = Menu;